<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onBeforeUnmount } from 'vue';

onMounted(() => {
  var chartDom = document.getElementById('graph-box');
  var myChart = echarts.init(chartDom);
  var option;

  option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['AI咨询', '冥想练习', '日记', '解压游戏', '心理测评'],
      icon: 'circle',
      top: '0px',
      left: '250px',
    },
    color: ['#54dcff', '#ff7ca3', '#6c9efe', '#ffbf53', '#50e3c2'],
    grid: {
      left: '3%',
      top: '50px',
      bottom: '0px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: ['20%', '10%'],
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    },
    yAxis: {
      type: 'value',
      // interval: 2000,
      splitNumber: 3,
      splitLine: {
        show: true, // 确保显示水平网格线
        lineStyle: {
          type: 'dashed', // 设置为虚线
          color: 'rgba(0, 0, 0, 0.2)' // 可选：设置颜色
        }
      },
    },
    series: [
      {
        name: 'AI咨询',
        type: 'line',
        smooth: true,
        showSymbol: false,
        // stack: 'Total',
        data: [4, 2, 4, 3, 4, 2, 1],
      },
      {
        name: '冥想练习',
        type: 'line',
        smooth: true,
        showSymbol: false,
        // stack: 'Total',
        data: [0, 1, 2, 5, 4, 2, 3]
      },
      {
        name: '日记',
        type: 'line',
        smooth: true,
        showSymbol: false,
        // stack: 'Total',
        data: [1, 5, 0, 4, 3, 2, 4]
      },
      {
        name: '解压游戏',
        type: 'line',
        smooth: true,
        showSymbol: false,
        // stack: 'Total',
        data: [1, 5, 4, 2, 4, 0, 2]
      },
      {
        name: '心理测评',
        type: 'line',
        smooth: true,
        showSymbol: false,
        // stack: 'Total',
        data: [5, 5, 2, 4, 1, 2, 5]
      }
    ]
  };

  // 设置图形配置
  option && myChart.setOption(option);

  // 监听窗口 resize 事件
  const handleResize = () => {
    myChart?.resize();
  };

  // 添加窗口变化的监听事件
  window.addEventListener('resize', handleResize);

  // 组件卸载前移除监听，防止内存泄漏
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    myChart?.dispose();
  });
})
</script>

<template>
<h2 style="padding: 20px 0 10px 0; text-align: center">AI心理自助使用情况</h2>
<div style="width: 840px;margin: 0 auto; padding-left: 10px; color: rgba(0, 0, 0, 0.5)">次数</div>
<div id="graph-box"></div>
</template>

<style scoped>
#graph-box {
  margin: 0 auto;
  width: 840px;
  height: 420px;
}
</style>